<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const ElMessage = {
  success: (message) => {
    console.log(`[ElMessage Success]: ${message}`);
    alert(`成功: ${message}`);
  },
  error: (message) => {
    console.error(`[ElMessage Error]: ${message}`);
    alert(`错误: ${message}`);
  },
  warning: (message) => {
    console.warn(`[ElMessage Warning]: ${message}`);
    alert(`警告: ${message}`);
  },
  info: (message) => {
    console.info(`[ElMessage Info]: ${message}`);
    alert(`信息: ${message}`);
  },
};

const ElMessageBox = {
  confirm: (message) => {
    return new Promise((resolve, reject) => {
      console.log(`[ElMessageBox Confirm]: ${message}`);
      if (window.confirm(message)) {
        resolve();
      } else {
        reject(new Error('Action cancelled by user'));
      }
    });
  }
};

const allTeachersInSelectedTeam = ref([]); 
const showBulkImportDialog = ref(false); 
const allUsersForAdd = ref([]); 
const selectedTeacherToAdd = ref(null); 
const selectedTeachersForImport = ref([]); 
const searchTeacherQuery = ref(''); 

const route = useRoute();

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
});

const filterableUsers = computed(() => {
  console.log('[Computed] filterableUsers: Recalculating...');
  if (!allUsersForAdd.value || allUsersForAdd.value.length === 0) {
    console.log('[Computed] filterableUsers: allUsersForAdd is empty or null/undefined.');
    return [];
  }

  const existingTeacherIds = new Set(allTeachersInSelectedTeam.value.map(t => t.userId));
  console.log('[Computed] filterableUsers: Existing teacher IDs in current course:', Array.from(existingTeacherIds));

  const filtered = allUsersForAdd.value.filter(user => !existingTeacherIds.has(user.userId));
  console.log('[Computed] filterableUsers: Filtered users (not in current course):', filtered);
  return filtered;
});


const filteredUsersForAdd = computed(() => {
  console.log('[Computed] filteredUsersForAdd: Recalculating...');
  if (!searchTeacherQuery.value) {
    console.log('[Computed] filteredUsersForAdd: No search query, returning all filterable users.');
    return filterableUsers.value;
  }
  const query = searchTeacherQuery.value.toLowerCase();
  const filtered = filterableUsers.value.filter(user =>
    user.userId.toLowerCase().includes(query) ||
    user.userName.toLowerCase().includes(query) ||
    user.userAccount.toLowerCase().includes(query)
  );
  console.log('[Computed] filteredUsersForAdd: Filtered by query "' + query + '":', filtered);
  return filtered;
});


const selectAllTeachers = computed({
  get() {
    // 只有当 filteredUsersForAdd 中有用户且所有用户都被选中时，全选框才为选中状态
    return filteredUsersForAdd.value.length > 0 && selectedTeachersForImport.value.length === filteredUsersForAdd.value.length;
  },
  set(value) {
    if (value) {
      // 选中所有当前过滤后的用户
      selectedTeachersForImport.value = filteredUsersForAdd.value.map(teacher => teacher.userId);
    } else {
      // 清空选中项
      selectedTeachersForImport.value = [];
    }
    console.log('[Computed] selectAllTeachers: selectedTeachersForImport updated to:', selectedTeachersForImport.value);
  }
});


// 获取当前课程的教师列表
const fetchTeachersForCourse = async (courseId) => {
  console.log(`[API Call] fetchTeachersForCourse: Fetching teachers for courseId: ${courseId}`);
  allTeachersInSelectedTeam.value = []; // 清空成员列表

  if (!courseId) {
    console.error('Error: Course ID not provided via props! Cannot fetch teachers.');
    ElMessage.error('无法获取课程ID，请确保父组件正确传递了courseId。');
    return;
  }

  const apiPath = `/api/courses/${courseId}/teachers/ids`;
  try {
    const response = await axios.get(apiPath);
    console.log('[API Response] fetchTeachersForCourse:', response);

    // 获取教师ID列表后，需要获取教师详细信息
    const teacherIds = Array.isArray(response) ? response : (response.data || []);
    const teachers = [];
    for (const teacherId of teacherIds) {
      try {
        const userRes = await axios.get(`/api/users/${teacherId}`);
        const userData = Array.isArray(userRes) ? userRes[0] : (userRes.data || userRes);
        teachers.push(userData);
      } catch (err) {
        console.error(`获取教师信息失败: ${teacherId}`, err);
      }
    }
    allTeachersInSelectedTeam.value = teachers;
    console.log('Teacher list fetched successfully:', allTeachersInSelectedTeam.value);
    
    if (teachers.length === 0 && teacherIds.length > 0) {
      ElMessage.warning('未能获取到有效的教师详细信息。');
    } else if (teacherIds.length === 0) {
      ElMessage.warning('当前课程暂无教师。');
    }

  } catch (error) {
    console.error('Failed to fetch teacher list:', error);
    ElMessage.error('获取教师列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    allTeachersInSelectedTeam.value = [];
  }
};


// 获取所有用户（用于添加教师）
const fetchAllUsers = async () => {
  console.log('[API Call] fetchAllUsers: Fetching all users from /api/users');
  try {
    const response = await axios.get('/api/users');
    // Assuming response.data is the array of users, or the response itself if interceptor returns data
    const users = Array.isArray(response) ? response : (Array.isArray(response.data) ? response.data : []);
    allUsersForAdd.value = users;
    console.log("All users fetched for adding (without initial role filtering):", allUsersForAdd.value);

    if (allUsersForAdd.value.length === 0) {
      ElMessage.warning('未能获取到可用的用户列表。');
    }
  } catch (error) {
    console.error('Failed to fetch all users:', error);
    ElMessage.error('获取所有用户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    allUsersForAdd.value = [];
  }
};


const confirmAddSingleTeacher = async () => {
  if (!selectedTeacherToAdd.value) {
    ElMessage.warning('请选择一个教师。');
    return;
  }
  const teacherId = selectedTeacherToAdd.value.userId;
  console.log(`[API Call] confirmAddSingleTeacher: Adding teacher ${teacherId} to course ${props.courseId}`);
  try {
    await axios.post(`/api/courses/${props.courseId}/teachers/${teacherId}`);
    ElMessage.success(`教师 ${selectedTeacherToAdd.value.userName} 添加成功！`);
    closeBulkImportDialog(); // 统一使用批量导入的关闭函数
    fetchTeachersForCourse(props.courseId); // 重新获取教师列表以更新UI
  } catch (error) {
    console.error('添加教师失败:', error);
    ElMessage.error('添加教师失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};


// 移除教师函数
const removeTeacherFromTeam = async (teacherId) => {
  console.log(`[API Call] removeTeacherFromTeam: Removing teacher ${teacherId} from course ${props.courseId}`);
  try {
    await ElMessageBox.confirm('确定要从当前课程中移除此教师吗？');
    await axios.delete(`/api/courses/${props.courseId}/teachers/${teacherId}`);
    ElMessage.success('教师移除成功！');
    fetchTeachersForCourse(props.courseId); // 重新获取教师列表以更新UI
  } catch (error) {
    console.error('移除教师失败:', error);
    if (error.message !== 'Action cancelled by user') {
      ElMessage.error('移除教师失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }
};

// 打开批量导入的模态框
const openBulkImportDialog = async () => {
  console.log('[UI Action] openBulkImportDialog: Opening bulk import modal.');
  selectedTeachersForImport.value = []; // 重置选中项
  searchTeacherQuery.value = ''; // 清空搜索框
  await fetchAllUsers(); // 获取所有用户用于选择
  showBulkImportDialog.value = true;
};


// 关闭批量导入的模态框
const closeBulkImportDialog = () => {
  console.log('[UI Action] closeBulkImportDialog: Closing bulk import modal.');
  showBulkImportDialog.value = false;
  selectedTeachersForImport.value = [];
  selectedTeacherToAdd.value = null; // 确保清除单选状态
};


// 批量添加教师函数
const bulkAddTeachers = async () => {
  if (selectedTeachersForImport.value.length === 0) {
    ElMessage.warning('请至少选择一个用户进行导入。');
    return;
  }

  console.log(`[API Call] bulkAddTeachers: Adding ${selectedTeachersForImport.value.length} users to course ${props.courseId}`);
  try {
    const results = await Promise.allSettled(
      selectedTeachersForImport.value.map(userId =>
        axios.post(`/api/courses/${props.courseId}/teachers/${userId}`)
          .then(() => ({ userId, status: 'fulfilled' }))
          .catch(error => ({ userId, status: 'rejected', error }))
      )
    );

    const successfulImports = results.filter(res => res.status === 'fulfilled');
    const failedImports = results.filter(res => res.status === 'rejected');

    if (successfulImports.length > 0) {
      ElMessage.success(`成功导入 ${successfulImports.length} 名用户！`);
    }

    if (failedImports.length > 0) {
      const failedUserIds = failedImports.map(res => res.userId).join(', ');
      ElMessage.error(`部分用户导入失败: ${failedUserIds}。详情请查看控制台。`);
      failedImports.forEach(f => console.error(`Failed to add user ${f.userId}:`, f.error));
    }

    closeBulkImportDialog();
    fetchTeachersForCourse(props.courseId); // 重新获取教师列表以更新UI
  } catch (error) {
    console.error('批量添加用户操作失败:', error);
    ElMessage.error('批量添加用户操作失败: ' + (error.message || '未知错误'));
  }
};


onMounted(() => {
  console.log('[Lifecycle] onMounted: Component mounted.');
  // Initial fetch is handled by the immediate watcher for props.courseId
});

watch(() => props.courseId, (newCourseId) => {
  console.log('[Watcher] props.courseId changed:', newCourseId);
  if (newCourseId) {
    fetchTeachersForCourse(newCourseId);
  } else {
    // If courseId becomes null, clear the list
    allTeachersInSelectedTeam.value = [];
    ElMessage.error('未检测到课程ID，请确保父组件通过props正确传递了courseId。');
  }
}, { immediate: true }); // immediate: true ensures this runs on component mount

// Removed redundant watch for route.params.courseId if props.courseId is always derived from it
// or is the primary source of truth. If route.params.courseId can change independently
// and you need to react to it, you would re-add it carefully.
// Given your current setup, props.courseId seems to be the main driver.

</script>

<template>
  <div class="teaching-team-management-page container-fluid">
    <h1 class="h2 page-title">
      教学团队管理
    </h1>

    <div class="row justify-content-center">
      <div class="col-lg-10 col-md-12">
        <div class="card shadow-sm data-card mt-4">
          <div class="card-header d-flex align-items-center justify-content-between">
            <h5 class="mb-0">
              课程教师成员列表
            </h5>
            <div class="teacher-actions">
              <button
                class="btn btn-sm btn-primary"
                @click="openBulkImportDialog"
              >
                <i class="bi bi-person-fill-add me-1" /> 添加/导入教师
              </button>
            </div>
          </div>
          <div class="card-body p-4">
            <div
              v-if="allTeachersInSelectedTeam.length === 0"
              class="alert alert-warning text-center"
              role="alert"
            >
              当前课程暂无教师信息。
            </div>
            <div
              v-else
              class="table-responsive"
            >
              <table class="table table-hover teacher-table">
                <thead>
                  <tr>
                    <th>教师ID</th>
                    <th>姓名</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="teacher in allTeachersInSelectedTeam"
                    :key="teacher.userId"
                  >
                    <td
                      class="teacher-id-col"
                      data-label="教师ID:"
                    >
                      {{ teacher.userId }}
                    </td>
                    <td
                      class="teacher-name-col"
                      data-label="姓名:"
                    >
                      {{ teacher.userName }}
                    </td>
                    <td class="teacher-actions-col">
                      <button
                        class="btn btn-sm btn-danger"
                        @click="removeTeacherFromTeam(teacher.userId)"
                      >
                        <i class="bi bi-person-dash-fill me-1" /> 移除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="showBulkImportDialog"
      class="modal-overlay"
    >
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              添加/导入教师到课程
            </h5>
            <button
              type="button"
              class="btn-close"
              @click="closeBulkImportDialog"
            />
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label
                for="teacherSearchFilter"
                class="form-label"
              >搜索用户（ID、姓名或账号）：</label>
              <input
                id="teacherSearchFilter"
                v-model="searchTeacherQuery"
                type="text"
                class="form-control"
                placeholder="输入用户ID、姓名或账号过滤"
              >
            </div>

            <div
              v-if="filteredUsersForAdd.length > 0"
              class="teacher-import-list mb-3"
              style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 0.5rem;"
            >
              <table class="table table-striped table-hover mb-0">
                <thead>
                  <tr>
                    <th style="width: 50px;">
                      <input
                        v-model="selectAllTeachers"
                        type="checkbox"
                      >
                    </th>
                    <th>用户ID</th>
                    <th>姓名</th>
                    <th>账号</th>
                    <th>角色ID</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="user in filteredUsersForAdd"
                    :key="user.userId"
                  >
                    <td>
                      <input
                        v-model="selectedTeachersForImport"
                        type="checkbox"
                        :value="user.userId"
                      >
                    </td>
                    <td>{{ user.userId }}</td>
                    <td>{{ user.userName }}</td>
                    <td>{{ user.userAccount }}</td>
                    <td>{{ user.roleId }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div
              v-else
              class="alert alert-info text-center"
            >
              暂无符合条件或已在当前课程中的用户可添加。
            </div>

            <div class="d-flex justify-content-end mt-4">
              <button
                type="button"
                class="btn btn-primary me-2"
                :disabled="selectedTeachersForImport.length === 0"
                @click="bulkAddTeachers"
              >
                <i class="bi bi-person-fill-add me-1" /> 确认添加 ({{ selectedTeachersForImport.length }})
              </button>
              <button
                type="button"
                class="btn btn-secondary"
                @click="closeBulkImportDialog"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import '../../assets/css/theme.css';

.teaching-team-management-page {
  padding: 1.5rem;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 1.5rem;
  color: #333;
}

.data-card {
  border: none;
  border-radius: 0.75rem;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  background-color: #ffffff;
}

.card-header {
  border-bottom: none;
  padding: 1.25rem 1.5rem;
  background-color: var(--primary);
  color: white;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top-left-radius: 0.75rem;
  border-top-right-radius: 0.75rem;
}

.card-body {
  padding: 1.5rem;
}


.team-details p {
  margin-bottom: 0.5rem;
  font-size: 1rem;
  color: #555;
}

.team-details strong {
  color: #333;
}


.teacher-table {
  width: 100%;
  margin-bottom: 0;
  border-collapse: separate;
  border-spacing: 0 0.5rem;
}

.teacher-table thead th {
  background-color: #f2f2f2;
  border-bottom: 2px solid var(--primary);
  padding: 1rem;
  font-weight: 600;
  color: #555;
  text-align: left;
  vertical-align: middle;
}

.teacher-table tbody tr {
  background-color: #fdfdfd;
  border-radius: 0.5rem;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.02);
  transition: all 0.2s ease-in-out;
}

.teacher-table tbody tr:hover {
  background-color: #eef;
  transform: translateY(-2px);
  box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.05);
}

.teacher-table tbody td {
  padding: 1rem;
  vertical-align: middle;
  border-top: none;
}


.teacher-table th:nth-child(1),
.teacher-table td.teacher-id-col {
  width: 25%;
  text-align: left;
}

.teacher-table th:nth-child(2),
.teacher-table td.teacher-name-col {
  width: 35%;
  text-align: left;
}

.teacher-table th:nth-child(3),
.teacher-table td.teacher-actions-col {
  width: 40%;
  text-align: right;
}


.btn {
  min-width: 80px;
  font-size: 0.85rem;
  padding: 0.5rem 0.9rem;
  border-radius: 0.3rem;
  transition: all 0.2s ease-in-out;
}

.btn-primary {
  background-color: var(--primary);
  border-color: var(--primary);
}

.btn-primary:hover {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
}

.btn-success {
  background-color: var(--success);
  border-color: var(--success);
}

.btn-success:hover {
  background-color: var(--success-dark);
  border-color: var(--success-dark);
}

.btn-info {
  background-color: var(--info);
  border-color: var(--info);
  color: white;
}

.btn-info:hover {
  background-color: var(--info-dark);
  border-color: var(--info-dark);
}

.btn-danger {
  background-color: var(--danger);
  border-color: var(--danger);
}

.btn-danger:hover {
  background-color: var(--danger-dark);
  border-color: var(--danger-dark);
}

.btn-secondary {
  background-color: var(--gray);
  border-color: var(--gray);
  color: white;
}

.btn-secondary:hover {
  background-color: var(--gray-dark);
  border-color: var(--gray-dark);
}

/* Modal Styling */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1050;
}

.modal-dialog {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  animation: fadeIn 0.3s ease-out;
}

/* For larger modal (e.g., bulk import, add single teacher) */
.modal-dialog.modal-lg {
  max-width: 800px;
}

.modal-content {
  border: none;
  border-radius: 0.75rem;
  overflow: hidden;
}

.modal-header {
  background-color: var(--primary);
  color: white;
  padding: 1.25rem 1.5rem;
  border-bottom: none;
}

.modal-title {
  font-size: 1.25rem;
  font-weight: 600;
}

.btn-close {
  filter: invert(1);
}

.modal-body {
  padding: 1.5rem;
}


/* Styles for teacher lists inside modals */
.teacher-list-for-add,
.teacher-import-list {
  border: 1px solid #e0e0e0;
  border-radius: 0.5rem;
}

.teacher-list-for-add .table tbody tr td,
.teacher-import-list .table tbody tr td {
  padding: 0.75rem 1.25rem;
  border-left: none;
  border-right: none;
  border-top: none;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {


  .teacher-table thead {
    display: none;
  }

  .teacher-table tbody,
  .teacher-table tr,
  .teacher-table td {
    display: block;
    width: 100%;
  }

  .teacher-table tbody tr {
    margin-bottom: 1rem;
    border: 1px solid #e0e0e0;
  }

  .teacher-table td {
    text-align: right;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 10px;
    padding-left: 10px;
  }

  .teacher-table td::before {
    content: attr(data-label);
    position: static;
    width: auto;
    text-align: left;
    font-weight: 600;
    flex-shrink: 0;
    margin-right: 10px;
  }

  /* Specific labels for teacher table cells */
  .teacher-table td.teacher-id-col::before {
    content: "教师ID:";
  }

  .teacher-table td.teacher-name-col::before {
    content: "姓名:";
  }

  .teacher-table td.teacher-actions-col::before {
    content: "操作:";
  }
}
</style>
